//
//  MHEventViewController.m
//  MHO
//
//  Created by papo on 3/3/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHEventViewController.h"
#import "Lib.h"
#import "Contants.h"
#import "UIImageView+WebCache.h"
#import "News.h"
#import "MHNewsCell.h"
#import "MHGameHotSlider.h"
#import "MHNavibarView.h"
#import "MHNewsDetailViewController.h"
#import "MHAppDelegate.h"


@interface MHEventViewController ()
{
    NSArray* data;
}
@property (nonatomic, strong) NSMutableArray* data;
@property (nonatomic, assign) int currentIndex;
@property (nonatomic, strong) NSArray* hotData;
@property (nonatomic, strong) MHGameHotSlider* hotSlider;
@property (nonatomic, strong) MHNavibarView* navibarView;

@end

@implementation MHEventViewController


-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.navibarView = [MHNavibarView createWithTitle:nil leftButton:kFileBtnHuman rightButton:nil searchButton:NO];
    [self.navibarView setActionSelectorDelegate:self left:@selector(backButtonPressed:) right:nil search:nil];
    [self.navibarView setRootViewController:self];
    [self.view addSubview:self.navibarView];
    [self reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)backButtonPressed: (id)sender {
    [[MHAppDelegate sharedApp].viewController showLeftPanelAnimated:YES];
//    [self.navigationController popViewControllerAnimated:YES];
}

- (void)refresh {
    [self.data removeAllObjects];
    self.data = nil;
    [self reloadData];
}

- (void)loadingMore {
    [self loadMore];
}

- (void)reloadData {
    if (self.data) {
        return;
    }
    [self loadFromIndex:0];
}

- (void)loadMore {
    [self loadFromIndex:self.currentIndex];
}

- (void)loadFromIndex: (int )index {
    [Lib showLoadingView];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSArray* arr = [News newsArrayFromUrl:[Contants urlForKey:[NSString stringWithFormat:@"http://api.mho.vn/services/news?typeid=2&gameid=%d&pageindex=%d&pagesize=%d", 0, index, 10]]];
        NSArray* arr = [News newsArrayFromUrl:[NSString stringWithFormat:@"http://api.mho.vn/services/news?typeid=2&gameid=0&pageindex=%ld&pagesize=10", (long)index]];
        if (index == 0 || !self.data) {
            self.data = [NSMutableArray arrayWithArray:arr];
        }
        else {
            for (id news in arr) {
                [self.data addObject:news];
            }
        }
        self.currentIndex = index + 1;
        self.hotData = [News getHotNews];
        
        // main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            [self stopLoading];
            [self stopLoadingMore];
            [self.tableView reloadData];
        });
    });
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section == 0) {
        return 1;
    }
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* CellIndentifier = @"Cell";
    if (indexPath.section == 0) {
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] init];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            self.hotSlider = [MHGameHotSlider sliderFromNib];
            
            NSMutableArray* viewsArray = [[NSMutableArray alloc] init];
            for (News* news in self.hotData) {
                NSURL* url = [Contants getImageUrl:news.imagePath width:320 height:120];
                if (url) {
                    [viewsArray addObject:url];
                }
            }
            [self.hotSlider.infiSlider setViewsArray:viewsArray];
            
            [cell.contentView addSubview:self.hotSlider];
        }
        return cell;
    }
    else {
        MHNewsCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
        if (!cell) {
            cell = [MHNewsCell cellFromNib];
        }
        // configure cell
        News* news = [self.data objectAtIndex:indexPath.row];
        
        [cell.imagePath setImageWithURL:[Contants getImageUrl:news.imagePath width:120 height:100]];
        cell.title.text = news.title;
        cell.lead.text = news.lead;
        cell.publishDate.text = news.publishDate;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 130;
    }
    return 90;
}

#pragma mark - UITableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        News* news = [self.data objectAtIndex:indexPath.row];
        //        if (news.urlDetail && ![news.urlDetail isKindOfClass:[NSNull class]] && news.urlDetail.length > 0) {
        //            MHNewsDetailViewController* vc = [[MHNewsDetailViewController alloc] initWithNibName:@"MHNewsDetailViewController" bundle:nil];
        //            [vc openUrl:news.urlDetail];
        //            [self presentModalViewController:vc animated:YES];
        //        }
        //        else
        {
            [Lib showLoadingView];
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                News* n = [News getDetailNews:[NSString stringWithFormat:@"%d", news.newsId]];
                
                // main thread
                dispatch_async(dispatch_get_main_queue(), ^{
                    [Lib removeLoadingView];
                    if (n.urlDetail) {
                        MHNewsDetailViewController* vc = [[MHNewsDetailViewController alloc] initWithNibName:@"MHNewsDetailViewController" bundle:nil];
                        vc.htmlString = n.content;
                        [self.navigationController pushViewController:vc animated:YES];
                    }
                });
            });
        }
    }
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];

    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
 
 */

@end
